<template>
  <div class="file-management">
    <el-card shadow="hover">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-medium">文件列表</span>
          <div>
            <el-button type="primary" size="small" @click="refreshList"> 刷新 </el-button>
            <el-button type="success" size="small" @click="openUploadDialog"> 文件上传 </el-button>
            <el-button type="primary" size="small" @click="showRecallTestDialog"
              >召回测试</el-button
            >
          </div>
        </div>
      </template>

      <el-dialog v-model="showUploadDialog" title="文件上传" width="50%">
        <FileUploadView
          v-model="showUploadDialog"
          @upload-success="handleUploadSuccess"
          @close-dialog="showUploadDialog = false"
          ref="fileUploadViewRef"
        />
      </el-dialog>

      <el-table
        :data="tableData"
        stripe
        border
        v-loading="loading"
        style="width: 100%; min-width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="文件名" min-width="150" />
        <el-table-column prop="typeName" label="类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.typeName)">
              {{ scope?.row?.typeName || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createAt" label="创建时间" width="180" align="center">
          <template #default="scope">
            <span>{{
              scope?.row?.createAt ? new Date(scope.row.createAt).toLocaleString() : '-'
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showChunkDialog(scope.row.id)"
              >查看分块</el-button
            >
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-dialog v-model="chunkDialogVisible" title="文件分块内容" width="70%">
          <div v-for="(chunk, index) in chunkData" :key="chunk.id" style="margin-bottom: 20px">
            <h4>分块 {{ index + 1 }}</h4>
            <el-card>
              <p>{{ chunk.content }}</p>
              <div v-if="chunk.keywords && chunk.keywords.length > 0">
                <h5>关键词:</h5>
                <el-tag v-for="(keyword, i) in chunk.keywords" :key="i" style="margin-right: 5px">
                  {{ keyword }}
                </el-tag>
              </div>
            </el-card>
          </div>
          <template #footer>
            <el-button @click="chunkDialogVisible = false">关闭</el-button>
          </template>
        </el-dialog>

        <el-dialog v-model="recallTestDialogVisible" title="召回测试" width="70%">
          <div style="display: flex; align-items: center; margin-bottom: 20px">
            <el-input
              v-model="recallQuestion"
              placeholder="请输入测试问题"
              style="flex: 1; margin-right: 10px"
            />
            <el-button type="primary" @click="handleRecallTest"> 测试 </el-button>
          </div>

          <el-table :data="recallResults" style="width: 100%; margin-top: 20px" border stripe>
            <el-table-column prop="name" label="文件名" width="180" align="center" />
            <el-table-column prop="typeName" label="类型" width="100" align="center">
              <template #default="scope">
                <el-tag :type="getTagType(scope.row.typeName)">
                  {{ scope.row.typeName || '未知' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="内容" min-width="300">
              <template #default="scope">
                <div
                  v-for="(chunk, index) in scope.row.chunks"
                  :key="chunk.id"
                  style="margin-bottom: 15px"
                >
                  <el-card shadow="hover" style="margin-bottom: 10px">
                    <p style="white-space: pre-wrap; line-height: 1.5">{{ chunk.content }}</p>
                  </el-card>
                  <div v-if="chunk.keywords && chunk.keywords.length > 0" style="margin-top: 5px">
                    <el-tag
                      v-for="(keyword, i) in chunk.keywords"
                      :key="i"
                      type="info"
                      style="margin-right: 5px; margin-bottom: 5px"
                    >
                      {{ keyword }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-dialog>

        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          v-if="false"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
interface Chunk {
  id: number
  content: string
  keywords?: string[]
}

interface FileItem {
  id: number
  name: string
  typeName?: string
  createAt?: string
  chunks?: Chunk[]
}

interface RecallResult {
  name: string
  typeName?: string
  chunks: Chunk[]
}
import { ref, onMounted } from 'vue'
import { ElPagination } from 'element-plus'
import { getFileList, getSegDataPage, recallTesting, deleteFile } from '@/api/fileApi'
import FileUploadView from './FileUploadView.vue'
import { ElLoading, ElMessage } from 'element-plus'
import type { TagProps } from 'element-plus'

const chunkDialogVisible = ref(false)
const chunkData = ref<Chunk[]>([])
const currentFileId = ref<number | null>(null)
const question = ref<string>('')
const recallLoading = ref<boolean>(false)

const handleDelete = async (id: number) => {
  try {
    const res = await deleteFile(id.toString())
    if (res.data.code === 200) {
      ElMessage.success(res.data.msg || '删除成功')
      refreshList()
    } else {
      ElMessage.error(res.data.msg || '删除失败')
    }
  } catch (error) {
    ElMessage.error('删除失败')
    console.error(error)
  }
}

const handleRecallTest = async () => {
  if (!recallQuestion.value || !recallQuestion.value.trim()) {
    ElMessage.warning('请输入问题')
    return
  }

  const loading = ElLoading.service({
    lock: true,
    text: '正在测试...',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  try {
    const res = await recallTesting(recallQuestion.value)
    if (res.data.code === 200) {
      if (res.data.data === null) {
        recallResults.value = []
        ElMessage.info('暂无承载数据')
      } else {
        recallResults.value = (res.data.data as FileItem[]).map((item) => ({
          ...item,
          chunks: item.chunks || [],
        }))
        ElMessage.success('召回测试成功')
      }
    } else {
      ElMessage.error(res.data.msg || '召回测试失败')
    }
  } catch (error: unknown) {
    if (error instanceof Error) {
      ElMessage.error('召回测试失败: ' + (error as Error).message)
    } else {
      ElMessage.error('召回测试失败')
    }
  } finally {
    loading.close()
  }
}

const showChunkDialog = async (fileId: number) => {
  currentFileId.value = fileId
  const loading = ElLoading.service({
    lock: true,
    text: '正在加载分块数据...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  try {
    const res = await getSegDataPage({ fileId })
    if (res.data.code === 200) {
      chunkData.value = res.data.data
      chunkDialogVisible.value = true
    } else {
      ElMessage.error('获取分块数据失败: ' + (res.msg || '未知错误'))
    }
  } catch (error) {
    console.error('获取分块数据失败:', error)
    ElMessage.error('获取分块数据失败: ' + (error as Error).message)
  } finally {
    loading.close()
  }
}

const fileUploadViewRef = ref<InstanceType<typeof FileUploadView>>()
const showUploadDialog = ref(false)

const openUploadDialog = () => {
  showUploadDialog.value = true
  fileUploadViewRef.value?.reset()
}

const showRecallTestDialog = () => {
  recallTestDialogVisible.value = true
}
const recallTestDialogVisible = ref(false)
const recallQuestion = ref('')
const recallResults = ref<RecallResult[]>([])

const loading = ref(true)
const tableData = ref([])
const pagination = ref({
  current: 1,
  size: 10,
  total: 0,
})

const getTagType = (typeName?: string): TagProps['type'] => {
  if (!typeName) return 'info'
  const types: Record<string, TagProps['type']> = {
    图片: 'success',
    文档: 'primary',
    视频: 'warning',
    音频: 'danger',
  }
  return types[typeName] || 'info'
}

const refreshList = async () => {
  try {
    loading.value = true
    const res = await getFileList({
      pageNum: pagination.value.current,
      pageSize: pagination.value.size,
    })

    console.log('API Response:', res) // 调试日志

    if (res?.data?.code === 200) {
      tableData.value = res.data.data?.records || []
      pagination.value.total = res.data.data?.total || 0
    } else {
      console.error('接口异常:', res?.data?.msg)
    }
  } catch (error) {
    console.error('请求失败:', error)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

const handleUploadSuccess = () => {
  refreshList()
  showUploadDialog.value = false
}

const handleSizeChange = (size: number) => {
  pagination.value.size = size
  refreshList()
}

const handleCurrentChange = (current: number) => {
  pagination.value.current = current
  refreshList()
}

onMounted(() => {
  refreshList()
})
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.file-management {
  width: 90%;
  margin: 0 auto;
  padding: 2% 0;
  box-sizing: border-box;
}

.el-table {
  width: 100% !important;
  min-width: auto !important;
}

.el-card {
  width: 100% !important;
  margin: 0 !important;
  padding: 2% !important;
  border-radius: 4px !important;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12) !important;
}

@media (max-width: 768px) {
  .file-management {
    width: 95%;
    padding: 1% 0;
  }

  .el-card {
    padding: 4% !important;
  }
}
</style>
